package com.hulytu.android.push.pushy;

import android.content.Context;
import android.text.TextUtils;

import com.hulytu.android.ThinDroid;
import com.hulytu.android.push.AppPush;

import org.jetbrains.annotations.NotNull;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import me.pushy.sdk.Pushy;
import me.pushy.sdk.util.exceptions.PushyException;

/**
 * Pushy 推送
 * <p>
 * https://pushy.me
 *
 * <p>
 * https://pushy.me/docs
 *
 * @Author: Chris
 * @CreateDate: 2021/8/6 10:53
 * @Description:
 */
public class MPushy extends AppPush {

    /**
     * 使用firebase服务
     */
    public static final String PARAM_USE_FCM = "useFCM";

    /**
     * Pushy 渠道初始化
     *
     * @param context 应用上下文
     * @param params  配置参数 如果使用了 firebase ， 可增加参数 {@link #PARAM_USE_FCM} 值为 <code>true</code>
     */
    @Override
    public void init(@NotNull Context context, Map<String, ?> params) {
        super.init(context, params);

        // 获取 deviceToken
        String deviceToken = getPushDeviceToken();
        if (TextUtils.isEmpty(deviceToken)) {
            ExecutorService service = Executors.newSingleThreadExecutor();
            service.execute(new RegisterTask());
            service.shutdown();
        } else {
            Pushy.listen(context);
        }

        Object useFCMObj = params == null ? null : params.get(PARAM_USE_FCM);

        boolean useFCM = useFCMObj instanceof Boolean && (boolean) useFCMObj;

        // Enable FCM Fallback Delivery
        Pushy.toggleFCM(useFCM, context);
    }

    @Override
    public String platform() {
        return "Pushy";
    }

    private final class RegisterTask implements Runnable {

        @Override
        public void run() {
            try {
                // Assign a unique token to this device
                String deviceToken = Pushy.register(getContext());

                // Save token locally / remotely
                setPushDeviceToken(deviceToken);

            } catch (PushyException e) {
                if (ThinDroid.isDebug()) e.printStackTrace();
            }
        }
    }
}
